package com.service.impl;

import com.baseEnum.SettingEnums;
import com.octo.captcha.service.CaptchaService;
import com.service.ICaptchaService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * @Author ri.yang
 * @Since 2016/1/6.
 */
@Service
public class CaptchaServiceImpl implements ICaptchaService {
    private CaptchaService imageCaptchaService;

    public BufferedImage buildImage(String captchaId) {
        return (BufferedImage) imageCaptchaService.getChallengeForID(captchaId);
    }

    public boolean isValid(SettingEnums.CaptchaType captchaType, String captchaId, String captcha) {
        if (captchaType == null || ArrayUtils.contains(SettingEnums.CaptchaType.getCaptchaTypes(), captchaType)) {
            if (StringUtils.isNotEmpty(captchaId) && StringUtils.isNotEmpty(captcha)) {
                try {
                    return imageCaptchaService.validateResponseForID(captchaId, captcha.toUpperCase());
                } catch (Exception e) {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public void setImageCaptchaService(CaptchaService imageCaptchaService) {
        this.imageCaptchaService = imageCaptchaService;
    }
}
